//
//  BookParkSpaceController.m
//  KuWeiPark
//
//  Created by Kevin Su on 15/4/30.
//  Copyright (c) 2015年 Clief. All rights reserved.
//

#import "BookParkSpaceController.h"
#import "AppMacro.h"
#import "HttpClientManager.h"
#import "MKScrollView.h"
#import "SVProgressHUD.h"
#import "AppDelegate.h"
#import "MainNavigationController.h"
#import "PersonalInfoViewController.h"
#import "MyOrderViewController.h"
#import "HomeViewController.h"
#import "TMCache.h"
#import "ParkingPortMapViewController.h"

@interface BookParkSpaceController ()<MKScrollViewDelegate, UIScrollViewDelegate, UITextFieldDelegate>

@end

@implementation BookParkSpaceController{
    
    MKScrollView *mkScrollView;
    UIImage *parkingPortImage;
    
    LoginModel *loginModel;
    ParkPortModel *parkingPortModel;
    
    ParkingPortMapViewController *parkingPortMapViewController;
    
    double unitePrice;
    double totalPay;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(executeUserChooseParkingspaceNotification:) name:Notify_ChooseParkingSpace object:nil];
    
    self.contentHeightConstraint.constant = self.addNewParkCarBtn.frame.size.height + self.addNewParkCarBtn.frame.origin.y + 100;
    
    self.addNewParkCarBtn.layer.masksToBounds = YES;
    self.addNewParkCarBtn.layer.cornerRadius = 5;
    self.addNewParkCarBtn.layer.borderColor = MAIN_GREEN_COLOR.CGColor;
    self.addNewParkCarBtn.layer.borderWidth = 1;
    
    self.payBtn.layer.masksToBounds = YES;
    self.payBtn.layer.cornerRadius = 3;
    self.payBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.payBtn.layer.borderWidth = 1;
    
    self.secondParkCarViewHeightConstraint.constant = 0;
    self.secondCarNoView.hidden = YES;
    
    self.firstCarNoTextField.delegate = self;
    self.secondCarNoTextField.delegate = self;
    self.navigationItem.title = self.parkAnnotationView.parkingSearchModel.name;
    self.parkingId = self.parkAnnotationView.parkingSearchModel.id;
    
    if([self.parkAnnotationView.parkingSearchModel.isBusy integerValue] == 0){
        
        self.type = BOOKPARKSPACE_TYPE_FREE;
        self.tipLabel.text = @"最多预约2个车位";
    }else{
        
        self.type = BOOKPARKSPACE_TYPE_BUSY;
        self.tipLabel.text = @"点击上方车位，最多预约2个车位";
    }
    
    loginModel = ApplicationDelegate.loginModel;
    self.firstCarNoTextField.text = loginModel.carNumber;
    totalPay = 0;
    [self updateBookResultLabel];
    
    [self getParkSpaceInfo];
}

- (void)viewDidDisappear:(BOOL)animated{
    
    mkScrollView = nil;
}

- (void)initParkportImageView{
    
    CGFloat imageWidth = [parkingPortModel.width floatValue];
    CGFloat imageHeight = [parkingPortModel.height floatValue];
    if(mkScrollView == nil){
        
        mkScrollView = [[MKScrollView alloc] init];
    }
    mkScrollView = [mkScrollView initWithPhoto:parkingPortImage Frame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width * imageHeight / imageWidth) Center:CGPointMake([parkingPortModel.centerX integerValue], [parkingPortModel.centerY integerValue])];
    mkScrollView.mkDelegate = self;
    [self.parkView addSubview:mkScrollView];
    
    self.parkViewHeightConstraint.constant = self.view.frame.size.width * imageHeight / imageWidth;
}

- (void)getparkingPortMapAtScene:(NSString *)scene{
    
    UIImage *savedImage = [[TMCache sharedCache] objectForKey:parkingPortModel.bigPic];
    if(savedImage == nil){
        
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", BASEURL, parkingPortModel.bigPic]]]];
        [[TMCache sharedCache] setObject:image forKey:parkingPortModel.bigPic];
        savedImage = image;
    }
    parkingPortImage = savedImage;
    
    if([scene isEqualToString:SCENE_PARKINGPORTMAP_NORMAL]){

        [self initParkportImageView];
    }else{

        [self showPopupParkingPortMap];
    }
    
}

- (void)updateBookResultLabel{
    
    //更新价格信息
    NSInteger parkPortNum = 0; //停车位数量
    if(self.selectedFirstParkingSpaceModel != nil){
        
        parkPortNum++;
    }
    
    if(self.selectedSecondParkingSpaceModel != nil){
        
        parkPortNum++;
    }
    
    self.bookResultLabel.text = [NSString stringWithFormat:@"预订车位数%i个  合计%.2f元", parkPortNum, parkPortNum * unitePrice];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - IBActions

- (IBAction)back:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)modifyFirstParkCarAction:(id)sender {
    
    //修改第一辆停车
}

- (IBAction)modifySecondParkCarAction:(id)sender {
    
    //修改第二辆停车
}

- (IBAction)addNewParkCarAction:(id)sender {
    
    //添加新的车牌号
    
}

- (IBAction)payAction:(id)sender {
    
    if([self.type isEqualToString:BOOKPARKSPACE_TYPE_BUSY]){
        
        //忙时 付款判断
        if(self.selectedFirstParkingSpaceModel == nil  && self.selectedSecondParkingSpaceModel == nil){
            
            [SVProgressHUD showErrorWithStatus:@"请选择停车位停车"];
            return;
        }
        
        if(self.selectedFirstParkingSpaceModel != nil && (self.firstCarNoTextField.text == nil || self.firstCarNoTextField.text.length == 0)){
            
            [SVProgressHUD showErrorWithStatus:@"请填写第一个停车位停车车辆"];
            return;
        }
        
        if(self.selectedSecondParkingSpaceModel != nil && (self.secondCarNoTextField.text == nil || self.secondCarNoTextField.text.length == 0)){
            
            [SVProgressHUD showErrorWithStatus:@"请填写第二个停车位停车车辆"];
            return;
        }
        
    }else{
        
        
    }
    
    NSString *firstParkingSpaceNo = self.selectedFirstParkingSpaceModel != nil? self.selectedFirstParkingSpaceModel.spaceNo : @"";
    NSString *secondParkingSpaceNo = self.selectedSecondParkingSpaceModel != nil? self.selectedSecondParkingSpaceModel.spaceNo : @"";
    
    //支付订金
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
    [[HttpClientManager sharedClient] payBookParkingSpaceRequestWithParkingId:self.parkingId
                                                                   WithUserId:loginModel.userId
                                            WithFirstpreBookingParkingSpaceNo:firstParkingSpaceNo
                                              WithFirstpreBookingParkingCarNo:self.firstCarNoTextField.text
                                           WithSecondpreBookingParkingSpaceNo:secondParkingSpaceNo
                                             WithSecondpreBookingParkingCarNo:self.secondCarNoTextField.text
                                                              WithSucessBlock:^(JsonRetMsg *response) {
        
        [SVProgressHUD showSuccessWithStatus:@"支付成功\n 即将进入导航..."];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self sendGuideNotification];
        });
                                                  
    } withFailedBlock:^(JsonRetMsg *responseObject) {
        
    }];
}

#pragma mark - 查看停车场大图 - 预约界面
- (void)singleTapDetected:(NSNumber *)pointX Y:(NSNumber *)pointY{
    
    //查看停车场大图
    if(parkingPortImage == nil){
        
        [self getparkingPortMapAtScene:SCENE_PARKINGPORTMAP_POPUP];
    }else{
        
        [self showPopupParkingPortMap];
    }
}

- (void)showPopupParkingPortMap{
    
    parkingPortMapViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ParkingPortMapViewController"];
    parkingPortMapViewController.parkingPortMap = parkingPortImage;
    parkingPortMapViewController.parkingPortModel = parkingPortModel;
    parkingPortMapViewController.selectedFirstParkingSpaceModel = self.selectedFirstParkingSpaceModel;
    parkingPortMapViewController.selectedSecondParkingSpaceModel = self.selectedSecondParkingSpaceModel;
    [self.navigationController pushViewController:parkingPortMapViewController animated:YES];
}

#pragma mark - 获取停车场信息

- (void)getParkSpaceInfo{
    
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
    [[HttpClientManager sharedClient] ParkingPortDetailRequestWithParkingId:self.parkingId WithUserId:loginModel.userId WithSucessBlock:^(JsonRetMsg *response) {
        
        [SVProgressHUD dismiss];
        
        parkingPortModel = [[ParkPortModel alloc] initWithDictionary:response.data error:nil];
        unitePrice = [parkingPortModel.unitPrice doubleValue];
        
        [self getparkingPortMapAtScene:SCENE_PARKINGPORTMAP_NORMAL];
        
    } withFailedBlock:^(JsonRetMsg *responseObject) {
        
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - 导航
- (void)sendGuideNotification{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:Notify_ShowGuideToParkPort object:nil userInfo:@{@"ParkAnnotationView":self.parkAnnotationView}];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 用户选择停车位导航信息
- (void)executeUserChooseParkingspaceNotification:(NSNotification *)notification{
    
    NSDictionary *userinfo = notification.userInfo;
    if(userinfo[@"FirstParkingSpace"] != nil){
        
        if(self.selectedFirstParkingSpaceModel == nil){
            
            //用户选择了第一个停车位
            self.selectedFirstParkingSpaceModel = userinfo[@"FirstParkingSpace"];
            [self showFirstParkView];
        }else{
            
            //维持现状
        }
        
    }else{
        
        if(self.selectedFirstParkingSpaceModel == nil){
            
            //维持现状
        }else{
            
            self.selectedFirstParkingSpaceModel = nil;
            [self hideFirstParkView];
        }
    }
    
    if(userinfo[@"SecondParkingSpace"] != nil ){
        
        if(self.selectedSecondParkingSpaceModel == nil){
            
            //用户选择了第二个停车位
            self.selectedSecondParkingSpaceModel = userinfo[@"SecondParkingSpace"];
            [self showSecondParkView];
        }else{
            
            //维持现状
        }
        
    }else{
        
        if(self.selectedSecondParkingSpaceModel == nil){
            
            //维持现状
        }else{
            
            self.selectedSecondParkingSpaceModel = nil;
            [self hideSecondParkView];
        }
    }
    
    [self updateBookResultLabel];
}

#pragma mark - 显示预约的停车位&车牌信息
- (void)hideFirstParkView{
    
    //隐藏 第一个 选择停车信息 的 视图
    [UIView animateWithDuration:0.3 animations:^{
        
        self.firstParkCarViewHeightConstraint.constant = 0;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
        self.firstCarNoView.hidden = YES;
    }];
}

- (void)showFirstParkView{
    
    //显示 第一个 选择停车信息 的 视图
    self.firstCarNoView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        self.firstParkCarViewHeightConstraint.constant = 50;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}

- (void)hideSecondParkView{
    
    //隐藏 第二个 选择停车信息 的 视图
    [UIView animateWithDuration:0.3 animations:^{
        
        self.secondParkCarViewHeightConstraint.constant = 0;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
        self.secondCarNoView.hidden = YES;
    }];
}

- (void)showSecondParkView{
    
    //编辑 第二个 选择停车信息 的 视图
    self.secondCarNoView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        self.secondParkCarViewHeightConstraint.constant = 50;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}


@end
